import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '_6_models/_1_user.dart';
import '_6_models/_2_people.dart';

class Demo extends StatelessWidget {
  const Demo({super.key});

  @override
  Widget build(BuildContext context) {
    // 1.1 数组的格式化
    //一个JSON格式的用户列表字符串
    String jsonStr = '[{"name":"Jack"},{"name":"Rose"}]';
//将JSON字符串转为Dart对象(此处是List)
    List items = json.decode(jsonStr);
    print("items: $items");
    String name = items[0]['name'];
    // 1.2 对象的格式化
    String jsonStr2 = '{"name": "Han li", "email": "john@example.com"}';
    Map<String, dynamic> user = json.decode(jsonStr2);
    String name2 = user['name'];
    // 2. Json对象格式化
    User userObj = User.fromJson(jsonStr2);
    String str = json.encode(userObj);
    // 3.自动生成Model
    String jsonStr3 =
        '{"name": "Han li", "email": "john@example.com", "user": {"name": "Han li", "email": "hanli@example.com"}}';
    Map<String, dynamic> peopleMap = json.decode(jsonStr3);
    People people = People.fromJson(peopleMap);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text("1. flutter自带json解码器 dart:convert"),
        Text("json.decode成数组获取用户名：$name"),
        Text("json.decode成对象获取用户名：$name2"),
        Text("直到运行时我们才知道值的类型，失去了大部分静态类型语言特性：类型安全、自动补全和最重要的编译时异常。"),
        Text("例如代码写的user['name3']，编译时不会报错，只有运行时根据数据来决定是否报错"),
        SizedBox(height: 30),
        Text("2. 所以需要Json Model化"),
        Text("User对象：${userObj.name}"),
        Text("User对象序列化为string，直接json.encode(userObj), $str"),
        SizedBox(height: 30),
        Text("3. 使用json_serializable package包"),
        Text("People对象：${people.name}; ${people.user.email}"),
        Text(
            "使用方法：1: 一次性生成：flutter packages pub run build_runner build ; 2: 自动生成：flutter packages pub run build_runner watch "),
        SizedBox(height: 30),
        Text("4. 命令方式实现json转dart类"),
        Text("原理还是一样的，占位符替换，生成代码"),
        SizedBox(height: 30),
        Text("5. 作者发布了一个 json_model 包, 好用吗？咋一直报错呢？"),
        GestureDetector(
          onTap: () async {
            await launchUrlString("https://github.com/flutterchina/json_model");
          },
          child: Text(
            "json_model github",
            style: TextStyle(
              color: Colors.blue, // 可以设置链接的颜色
              decoration: TextDecoration.underline, // 可以添加下划线
            ),
          ),
        ),
      ],
    );
  }
}

void main(List<String> args) {
  print("Hello World");

  runApp(MaterialApp(home: Scaffold(body: Demo())));
}
